package com.vcourse.cloud.sms.controller;

import com.aliyuncs.exceptions.ClientException;
import com.vcourse.commons.result.R;
import com.vcourse.commons.result.ResultCodeEnum;
import com.vcourse.commons.utils.FormUtils;
import com.vcourse.commons.utils.RandomUtils;
import com.vcourse.service.base.exception.CustomException;
import com.vcourse.cloud.sms.service.SmsService;
import com.vcourse.service.base.service.RedisService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author Zengsh123
 * @date 2020-06-08 16:26
 */
@Api("短信管理")
@RestController
@RequestMapping("/cloud/sms")
@Slf4j
public class ApiSmsController {
    @Resource
    private SmsService smsService;
    @Resource
    private RedisService redisService;
    @Value("redis.database")
    private String REDIS_DATABASE;
    @Value("redis.key")
    private String REDIS_KEY;

    @GetMapping("send/{mobile}")
    public R getCode(@PathVariable String mobile) throws ClientException {

        //校验手机号是否合法
        if(StringUtils.isBlank(mobile) || !FormUtils.isMobile(mobile)) {
            log.error("请输入正确的手机号码 ");
            throw new CustomException(ResultCodeEnum.LOGIN_PHONE_ERROR);
        }

        //生成验证码
        String checkCode = RandomUtils.getFourBitRandom();
        //发送验证码
        smsService.send(mobile, checkCode);
        //将验证码存入redis缓存
        redisService.set(REDIS_DATABASE + ":" + REDIS_KEY + ":" + mobile, checkCode, 300L);

        return R.ok().message("短信发送成功");
    }
}
